<?php

class Model_Acl extends Zend_Acl
{
    protected static $_instance = null;

    /**
     * 构造函数
     *
     */
    protected function __construct ()
    {
        $roles = new Model_DbTable_Role();
        $resources = new Model_DbTable_Resources();
        $permissions = new Model_DbTable_Permissions();
        // 注册角色
        foreach ($roles->fetchAll() as $role) {
            // 处理角色的继承
            if ($role->parent_rid) {
                $this->addRole(new Zend_Acl_Role($role->rname), new Zend_Acl_Role($role->findParentRow('Model_DbTable_Role')->rname));
            } else {
                $this->addRole(new Zend_Acl_Role($role->rname));
            }
        }
        // 注册资源
        foreach ($resources->fetchAll() as $resource) {
            // 处理资源继承
            if ($resource->parent_resid) {
                $this->add(new Zend_Acl_Resource($resource->resname), new Zend_Acl_Resource($resource->findParentRow('Model_DbTable_Resources')->resname));
            } else {
                $this->add(new Zend_Acl_Resource($resource->resname));
            }
        }
        // 处理授权
        foreach ($permissions->fetchAll() as $permission) {
            if (strcasecmp($permission->access, 'allow') == 0) {
                $this->allow($permission->findParentRow('Model_DbTable_Role', 'Role')->rname, $permission->findParentRow('Model_DbTable_Resources', 'Resources')->resname);
            } else { // Deny by default
                $this->deny($permission->findParentRow('Model_DbTable_Role', 'Role')->rname, $permission->findParentRow('Model_DbTable_Resources', 'Resources')->resname);
            }
        }
        //赋于超级管理员所有权限
        $this->allow('administrator');
    }

    static function getInstance (Zend_Cache_Core $cache, $force = false)
    {
        if (($acl = $cache->load('hmcms_acl')) && ! $force) {
            return $acl;
        } else {
            if (null === self::$_instance) {
                self::$_instance = new self();
                $cache->save(self::$_instance,'hmcms_acl');
            }
            return self::$_instance;
        }
    }

    static function refresh (Zend_Cache_Core $cache)
    {
        self::$_instance = new self();
        $cache->remove('hmcms_acl');
        $cache->save(self::$_instance,'hmcms_acl');
        return self::$_instance;
    }
}

